import { getToken, setToken } from '@/utils/auth' // 导入内部封装的cookie方法
import { sysLogin } from '@/api/login' // 登录api接口
import { sysProfile, sysUser } from '@/api/user' // 获取用户信息接口
import { Message } from 'element-ui' //  ===this.$message
import asyncRouters from '@/router/modules/index'
import Router from '@/router'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken() || '', // 从cookie中取值，没有为''
  userInfo: ''
}

const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value) // 保存到cookie中
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout() {
    // this==this.$store
    this.commit('user/setToken', '')
    this.commit('user/setUserInfo', '')
    resetRouter()
  }
}

const actions = {
  async toLogin(store, form) {
    const res = await sysLogin(form)
    Message.success('登录成功')
    store.commit('setToken', res.data) // 获取后调用setToken 将data存到cookie
    console.log(res)
  },
  async getUserinfo(store) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    store.commit('setUserInfo', Object.assign({}, res.data, res2.data))

    const newArr = asyncRouters.filter((item) => {
      return res.data.roles.menus.includes(item.meta.name)
    })

    Router.addRoutes([...newArr, { path: '*', redirect: '/404', hidden: true }])
    console.log(newArr, 'newArr')
    const allRouters = [
      ...constantRoutes,
      ...newArr,
      { path: '*', redirect: '/404', hidden: true }
    ]
    store.commit('routers/setRouterList', allRouters, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
